# -*- coding:utf-8 -*-
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import  post_save, pre_delete
from django.dispatch.dispatcher import receiver

from filebrowser.sites import site
from django.core.files.storage import default_storage
from filebrowser.fields import FileBrowseField
from mptt.fields import TreeForeignKey
from mptt.models import MPTTModel


#class AbstractColumn(models.Model):
#    parent = models.ForeignKey('self', null=True, blank=True, verbose_name='父栏目')
#
#    class Meta:
#        abstract = True

STATUS_YES_IMAGE_URL = '/static/images/my/yes.png'
STATUS_NO_IMAGE_URL = '/static/images/my/no.png'

class Column(MPTTModel):
    parent = models.ForeignKey('self', blank=True, null=True, related_name='children', verbose_name='父栏目')
    title = models.CharField(max_length=50, verbose_name='栏目名称')
    content = models.TextField(verbose_name='内容', blank=True, null=True)
    intro = models.CharField(max_length=50, verbose_name='介绍', blank=True)
    slug = models.CharField(max_length=15, verbose_name='URL', blank=True)


    def trver_list(self):
        tl = []
        node = self
        while node:
            tl.append(node)
            node = node.parent
        return  reversed(tl)

    def is_root_column(self):
        if self.is_root_node():
            return '<img src="%s" />' % STATUS_YES_IMAGE_URL
        else:
            return '<img src="%s" />' % STATUS_NO_IMAGE_URL

    is_root_column.short_description = '主栏目'
    is_root_column.allow_tags = True


    def article_count(self):
        return self.article_set.count()

    article_count.short_description = '文章数量'


    @staticmethod
    def first_id():
        if not Column.objects.count():
            return 0
        else:
            return Column.objects.all()[0].pk


    class Meta:
        verbose_name = '栏目'
        verbose_name_plural = verbose_name


    def __unicode__(self):
        return unicode(self.title)


class Article(models.Model):
    column = TreeForeignKey(Column, verbose_name='栏目')
    title = models.CharField(max_length=50, verbose_name='标题')
    content = models.TextField(verbose_name='内容', blank=True, null=True)
    pub_date = models.DateTimeField(verbose_name='发表时间', auto_now_add=True)


    @staticmethod
    def first_id():
        if not Article.objects.count():
            return 0
        else:
            return Article.objects.all()[0].pk


    def __unicode__(self):
        return unicode(self.title)

    class Meta:
        ordering = ['-pub_date']
        get_latest_by = 'pub_date'
        verbose_name = '文章'
        verbose_name_plural = verbose_name


class DownloadItem(models.Model):
    article = models.ForeignKey(Article, verbose_name='文章')
    title = models.CharField(max_length=50, verbose_name='标题')
    #file_item = models.FileField(verbose_name='文件', upload_to='/upload')
    file_item = FileBrowseField(verbose_name="上传文件", max_length=200, directory='resources/',
        extensions=['.ppt', '.doc', '.rmvb', '.avi', '.rm', '.rar', '.zip', 'xls'],
        blank=True, null=True)

    def used_by_article(self):
        return self.article.title
    used_by_article.short_description = '所属文章'

    class Meta:
        verbose_name = '下载'
        verbose_name_plural = verbose_name


    def __unicode__(self):
        return unicode(self.title)


class Question(models.Model):
    asker = models.CharField(max_length=50, verbose_name='提问者')
    content = models.TextField(verbose_name='问题')
    pub_date = models.DateTimeField(verbose_name='发表时间', auto_now_add=True)
    status = models.BooleanField(verbose_name='已回答', default=False)

    def __unicode__(self):
        return u'%s的问题' % self.asker

    class Meta:
        verbose_name = '问题'
        verbose_name_plural = verbose_name
        ordering = ['-pub_date']
        get_latest_by = 'pub_date'


class Answer(models.Model):
    question = models.ForeignKey(Question, verbose_name='问题')
    solver = models.ForeignKey(User, verbose_name='回答者')
    content = models.TextField(verbose_name='答案', blank=True, null=True)
    pub_date = models.DateField(verbose_name='回答时间', auto_now_add=True)

    def __unicode__(self):
        return u'%s的回答' % self.solver.username


    class Meta:
        verbose_name = '回答'
        verbose_name_plural = verbose_name
        ordering = ['-pub_date']
        get_latest_by = 'pub_date'


def delete_fileitem(sender, **kwargs):
    item = kwargs['instance']
    default_storage.delete(item.file_item.path, DownloadItem)


@receiver(post_save, sender=Answer)
def answer_added(sender, **kwargs):
    if kwargs['created']:
        answer = kwargs['instance']
        question = answer.question
        if not question.status:
            question.status = True
            question.save()


@receiver(pre_delete, sender=Answer)
def answer_deleted(sender, **kwargs):
    answer = kwargs['instance']
    question = answer.question
    if question.answer_set.count() == 1:
        question.status = False
        question.save()


site.filebrowser_post_delete.connect(delete_fileitem, DownloadItem)



